package com.swdegao.iot.netty.mqtt.degaoserver;


import com.swdegao.iot.netty.mqtt.MqttPushClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;



@Component
//@ConfigurationProperties("spring.mqtt")
@Data
public class MqttConfig {
    @Autowired
    private MqttPushClient mqttPushClient;

    /**
     * 用户名
     */
    @Value("${spring.mqtt.username}")
    private String username;
    /**
     * 密码
     */
    @Value("${spring.mqtt.password}")
    private String password;
    /**
     * 连接地址
     */
    @Value("${spring.mqtt.hostUrl}")
    private String hostUrl;
    /**
     * 客户Id
     */
    @Value("${spring.mqtt.clientId}")
    private String clientId;
    /**
     * 默认连接话题
     */
    @Value("${spring.mqtt.defaultTopic}")
    private String defaultTopic;
    /**
     * 超时时间
     */
    @Value("${spring.mqtt.timeout}")
    private int timeout;
    /**
     * 保持连接数
     */
    @Value("${spring.mqtt.keepalive}")
    private int keepalive;
    /**
     * mqtt功能使能
     */
    @Value("${spring.mqtt.enabled}")
    private boolean enabled;


    @Bean
    public MqttPushClient getMqttPushClient() {

        if(enabled == true){
            String mqtt_topic[] = defaultTopic.split(",");
            mqttPushClient.connect(hostUrl, clientId, username, password, timeout, keepalive);//连接
            for(int i=0; i<mqtt_topic.length; i++){
                mqttPushClient.subscribe(mqtt_topic[i], 0);//订阅主题
            }
        }
        return mqttPushClient;
    }
}


